/*
  * Mirante Tecnologia
  * Copyright 2010, Mirante Informatica LTDA, 
  * and individual contributors as indicated by the @authors tag
  *
  * This is free software; you can redistribute it and/or modify it
  * under the terms of the GNU Lesser General Public License as
  * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
package com.miranteinfo.seam.interceptor;

import org.hibernate.validator.InvalidStateException;
import org.hibernate.validator.InvalidValue;
import org.jboss.seam.annotations.intercept.AroundInvoke;
import org.jboss.seam.annotations.intercept.Interceptor;
import org.jboss.seam.intercept.InvocationContext;
import org.jboss.seam.log.Log;
import org.jboss.seam.log.Logging;

import com.miranteinfo.seam.interceptor.annotation.ExceptionsLogInterceptor;

/**
 * Interceptor criado para interceptar todas as excecoes e realizar seus respectivos logs.
 * 
 * @author lucas lins
 *
 */
@Interceptor(around = BusinessMessageInterceptorImpl.class)
public class ExceptionsLogInterceptorImpl {
	
	private Log log = Logging.getLog(ExceptionsLogInterceptor.class);
	
	@AroundInvoke
	public Object intercept(InvocationContext invocation) throws Exception {
		try{
			return invocation.proceed();
		}catch(Exception e){
			
			if(e instanceof InvalidStateException){
				InvalidStateException ise = (InvalidStateException) e;
				StringBuilder error = new StringBuilder();
				for(InvalidValue iv : ise.getInvalidValues()){
					error.append(" [ ");
					error.append(iv.getBeanClass().getName() + "->" +iv.getPropertyName() + ": " + iv.getMessage());
					error.append(" ] ");
				}
				log.warn("Invalid Values: " + error.toString());
			}

			log.warn(e.getLocalizedMessage(),e);
			
			throw e;
		}
	}
	
}
